import re

from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from goods.serializers import GoodsSerializer
from user_operation.models import UserFav, UserLeavingMessage, UserAddress


class UserFavDetailSerializer(serializers.ModelSerializer):
    """
    用户收藏详情序列化类
    """
    goods = GoodsSerializer()

    class Meta:
        model = UserFav
        fields = ("goods", )


class UserFavSerializer(serializers.ModelSerializer):
    """
    用户收藏序列化
    """
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = UserFav
        fields = ("user", "goods", "id")
        # 设置联合索引
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=("user", "goods"),
                message="已经收藏"
            )
        ]


class LeavingMessageSerializer(serializers.ModelSerializer):
    """
    用户留言序列化类
    """
    # 获取当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = UserLeavingMessage
        fields = ("user", "message_type", "subject", "message", "file", "id", "add_time")


class AddressSerializer(serializers.ModelSerializer):
    """
    用户收获地址序列化类
    """
    # 获取当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    def validate_signer_mobile(self, signer_mobile):
        """
        验证手机号码
        :param signer_mobile:
        :return:
        """
        # 验证手机号是否注册

        if UserAddress.objects.filter(signer_mobile=signer_mobile, user_id=self.context['request'].user.id).count():
            raise serializers.ValidationError(f'该用户已使用手机号{signer_mobile}添加地址')
        # 验证手机号是合法
        if not re.match(settings.REGEX_MOBILE, signer_mobile):
            raise serializers.ValidationError('手机号码非法')

        return signer_mobile

    class Meta:
        model = UserAddress
        fields = ("id", "user", "province", "city", "district", "address", "signer_name", "add_time", "signer_mobile")
